package com.tengju.motivation.infrastructure.repository.activity.convert;

import com.fasterxml.jackson.core.type.TypeReference;
import com.tengju.motivation.domain.model.activity.ActivityId;
import com.tengju.motivation.domain.model.activity.ActivityTarget;
import com.tengju.motivation.domain.model.activity.ActivityTargetType;
import com.tengju.motivation.domain.model.activity.TargetId;
import com.tengju.motivation.domain.model.goods.GoodsType;
import com.tengju.motivation.domain.shared.IdObject;
import com.tengju.motivation.domain.shared.JsonUtil;
import com.tengju.motivation.infrastructure.persistence.mybatis.dataobject.MotivationActivityTargetDetailDO;

import java.util.Optional;

public class ActivityTargetConvert {

    private ActivityTargetConvert() {
    }


    public static MotivationActivityTargetDetailDO domainToDo(ActivityTarget target) {

        if (target == null) {
            return null;
        }

        return new MotivationActivityTargetDetailDO(
                Optional.ofNullable(target.getTargetId()).map(IdObject::getValue).orElse(null),
                target.getActivityId().getValue(),
                0L,
                target.getActivityTime(),
                target.getTargetTitle(),
                target.getTargetType().getVal(),
                target.getTargetValue(),
                target.getTargetSubjectType().getVal(),
                target.getTargetSubjectId().toString(),
                target.getTargetReferStartTime(),
                target.getTargetReferEndTime(),
                target.getTargetSubjectType().getVal(),
                JsonUtil.toJSONString(target.getTargetCompareSubjects())
        );
    }

    public static ActivityTarget doToDomain(MotivationActivityTargetDetailDO detailDO) {
        if (detailDO == null) {
            return null;
        }

        return new ActivityTarget(
                new TargetId(detailDO.getTargetId()),
                new ActivityId(detailDO.getActivityId()),
                detailDO.getActivityDate(),
                detailDO.getTargetTitle(),
                detailDO.getTargetValue(),
                ActivityTargetType.fromVal(detailDO.getTargetType()),
                GoodsType.fromVal(detailDO.getTargetSubjectType()),
                Long.parseLong(detailDO.getTargetSubjects()),
                detailDO.getTargetReferStartTime(),
                detailDO.getTargetReferEndTime(),
                GoodsType.fromVal(detailDO.getTargetCompareSubjectType()),
                JsonUtil.toList(detailDO.getTargetCompareSubjects(), new TypeReference<>() {
                })
        );

    }
}
